<template>
	<div class="table-box">
		<div class="title" style="padding: 10px 20px; font-size: 26px; background-color: gray">比赛分组</div>
		<el-card style="margin-bottom: 10px; border-radius: 0">
			<el-space alignment="normal" direction="vertical">
				<div>
					{{ projectHeaderInfo.competitionName }}
				</div>
				<div>比赛项目： {{ projectHeaderInfo.projectNmae }}</div>
				<div style="font-weight: bold">场次：预赛第一场</div>
			</el-space>
		</el-card>
		<el-card style="margin: 10px 0">
			<el-button :icon="CirclePlus" @click="handleAddApplictionClick" type="primary">添加报名</el-button>
			<el-button plain type="primary" @click="handleStartMatchClcik">预赛分组</el-button>
		</el-card>
		<el-table
			:data="tableData"
			border
			style="width: 100%"
			row-key="competeTeamId"
			:default-expand-all="competitionProjectType == 1"
		>
			<el-table-column v-if="competitionProjectType == 1" label="参赛队名" align="center" property="competeTeamName" />
			<el-table-column label="参赛人" align="center" property="competeName" />
			<el-table-column label="联系电话" align="center" :formatter="phoneFormat" property="competeTel" />
			<el-table-column label="身份证" align="center" property="competeIdNo" />
			<el-table-column label="感应器" align="center" property="sensor" />
		</el-table>
		<!-- 预赛分组 -->
		<el-dialog width="40%" v-model="dialogShow">
			<template #header>
				<span class="dialog-footer">
					{{ projectHeaderInfo.competitionName + projectHeaderInfo.projectNmae + "预赛第一场分组" }}
				</span>
			</template>
			<div class="worning">
				<el-icon color="red" size="60"><WarnTriangleFilled /></el-icon>
				注意：如果已存在分组，会删掉以前分组，进行重新分组
			</div>
			<el-form
				ref="ruleFormRef"
				:model="GroupingFrom"
				:rules="rules"
				label-width="120px"
				class="demo-ruleForm"
				label-position="left"
				status-icon
			>
				<el-form-item :label="competitionProjectType == 2 ? '参赛总人数' : '参赛总队数'" prop="total">
					<el-input v-model.number="GroupingFrom.total" disabled />
				</el-form-item>
				<el-form-item :label="competitionProjectType == 2 ? '每组最少人数' : '每组最少队数'" prop="min">
					<el-input v-model.number="GroupingFrom.min" :min="1" />
				</el-form-item>
				<el-form-item :label="competitionProjectType == 2 ? '每组最大人数' : '每组最大队数'" prop="max">
					<el-input v-model.number="GroupingFrom.max" :min="1" />
				</el-form-item>
				<el-form-item label="分组数" prop="groupingNumber">
					<el-input v-model.number="GroupingFrom.groupingNumber" />
				</el-form-item>
				<!-- <el-form-item label="每组人数" prop="perNum">
					<el-input v-model="GroupingFrom.perNum" />
				</el-form-item> -->
				<el-form-item>
					<el-button @click="dialogShow = false">取消</el-button>
					<el-button type="primary" @click="handleConfrimClick(ruleFormRef)">确定</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
		<!-- 分组  -->
		<el-dialog
			@closed="handleCancelGroupingClick"
			:fullscreen="true"
			:show-close="false"
			class="garoup-dialog"
			v-model="groupingModel.isShow"
		>
			<template #default>
				<el-button class="close-btn" :icon="CircleCloseFilled" circle type="danger" @click="handleCancelGroupingClick" />
				<el-divider content-position="center"><strong style="font-size: 30px">分组</strong></el-divider>
				<div>
					<div class="groupingModel-header">
						<div></div>
						<div style="margin-right: 15px">
							<el-button size="large" @click="handleAddGrouped" type="primary">添加分组</el-button>
							<el-button size="large" @click="handleRest" type="info">重新分组</el-button>
						</div>
					</div>
					<div class="table_box_drag">
						<div class="table_main_drag" v-for="(item, i) in groupingModel.data" :key="i">
							<div class="card-header">
								<span style="font-size: 22px; font-weight: bold">{{ letterNumber(i) }}组</span>
								<div>
									<el-button size="small" @click="handleDeleteMemberClick(item, i)" type="warning">
										{{ competitionProjectType == 1 ? "删除队伍" : "删除人员" }}</el-button
									>
									<el-button size="small" @click="handleSelectMenberClick(item, i)" type="primary">
										{{ competitionProjectType == 1 ? "选择队伍" : "选择人员" }}
									</el-button>
									<el-button size="small" @click="handleLotteryClick(item, i)" type="primary">随机赛道</el-button>
									<el-button size="small" @click="handleDeleteGroupClick(item, i)" type="danger">删除分组</el-button>
								</div>
							</div>
							<draggable
								v-model="groupingModel.data[i]"
								group="site"
								animation="300"
								dragClass="dragClass"
								ghostClass="ghostClass"
								chosenClass="chosenClass"
								itemKey="id"
								tag="table"
								@start="onStart"
								@end="onEnd"
							>
								<template #header>
									<thead>
										<tr>
											<th>选择</th>
											<th>号位</th>
											<th>{{ competitionProjectType == 1 ? "队伍名称" : "姓名" }}</th>
											<th>{{ competitionProjectType == 1 ? "操作" : "传感器" }}</th>
										</tr>
									</thead>
								</template>
								<template #item="{ element, index }">
									<tr style="cursor: crosshair" :key="element.id" class="el-table__row">
										<td><el-checkbox v-model="element.isChecked" size="small" /></td>
										<td>{{ index + 1 }}</td>
										<td>{{ element.competeName || element.competeTeamName }}</td>
										<td v-if="competitionProjectType == 2">
											<el-input style="width: auto" v-model="element.sensor"></el-input>
										</td>
										<td v-else>
											<el-tag @click="handleEiditTeamInfoClick(element.children, index, i)" style="cursor: pointer"
												>编辑队伍信息</el-tag
											>
										</td>
									</tr>
								</template>
							</draggable>
						</div>
					</div>
					<div v-if="notGroupedMember.length" class="notGrouped">
						<el-divider content-position="left">{{ competitionProjectType == 1 ? "未分组队伍" : "未分组队伍" }}</el-divider>
						<table class="table table-bordered table-hover">
							<thead>
								<tr>
									<th>{{ competitionProjectType == 2 ? "姓名" : "队伍名" }}</th>
									<th v-if="competitionProjectType == 2">传感器</th>
								</tr>
							</thead>
							<tbody>
								<tr v-for="(item, index) in notGroupedMember" :key="index">
									<el-tooltip
										class="box-item"
										effect="dark"
										:content="item.competeTeamName || item.competeName"
										placement="top-start"
									>
										<td>{{ item.competeName || item.competeTeamName }}</td>
									</el-tooltip>
									<el-tooltip class="box-item" effect="dark" :content="item.sensor" placement="top-start">
										<td v-if="competitionProjectType == 2">{{ item.sensor }}</td>
									</el-tooltip>
								</tr>
							</tbody>
						</table>
					</div>
				</div>
				<el-dialog v-model="eiditModel" width="60%" title="编辑团队成员信息" append-to-body>
					<el-table :data="eiditTableData" style="width: 100%">
						<el-table-column prop="competeName" label="姓名" />
						<!-- <el-table-column prop="competeIdNo" label="身份证" width="200" /> -->
						<el-table-column label="传感器">
							<template #default="scope">
								<el-input v-model="scope.row.sensor" />
							</template>
						</el-table-column>
					</el-table>
					<template #footer>
						<span class="dialog-footer">
							<el-button size="large" @click="eiditModel = false">取消</el-button>
							<el-button size="large" type="primary" @click="handleEiditTableTeamClick"> 确定 </el-button>
						</span>
					</template>
				</el-dialog>
			</template>
			<template #footer>
				<span class="dialog-footer">
					<el-button size="large" @click="handleCancelGroupingClick">取消</el-button>
					<el-button size="large" type="primary" @click="handleCorifmClick"> 确定 </el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 添加报名 -->
		<el-dialog @closed="handleCancelClick(ruleFormRef)" v-model="ApplicationModle" width="40%">
			<template #header>
				<p>添加报名</p>
			</template>
			<!-- 报名表单 -->
			<el-form ref="ruleFormRef" label-width="150px" :model="applicationFrom">
				<div v-for="(item, index) in applicationFrom.EmployeeInfos" :key="index" class="person_item">
					<el-form-item
						v-if="competitionProjectType == 1"
						:prop="`EmployeeInfos.${index}.CompeteTeamName`"
						label="参赛队名："
						:rules="{
							required: true,
							message: '请输入参赛队名!',
							trigger: 'blur'
						}"
					>
						<el-input v-model="item.CompeteTeamName" placeholder="请输入" />
					</el-form-item>
					<el-form-item
						label="参赛人姓名："
						:prop="`EmployeeInfos.${index}.CompeteName`"
						:rules="{ required: true, message: '请输入姓名!', trigger: 'blur' }"
					>
						<el-input v-model="item.CompeteName" placeholder="请输入" />
					</el-form-item>
					<el-form-item
						label="参赛人联系电话："
						:prop="`EmployeeInfos.${index}.CompeteTel`"
						:rules="[
							{
								required: false,
								message: '请输入参赛人联系电话！',
								trigger: 'blur'
							},
							{
								pattern: /^(13[0-9]|14[1|4|5|6|7|8|9]|15[0|1|2|3|5|6|7|8|9]|17[2|3|5|6|7|8]|18[0-9]|19[1|8|9])\d{8}$/,
								message: '手机号格式不正确',
								trigger: 'blur'
							}
						]"
					>
						<el-input v-model="item.CompeteTel" placeholder="请输入" />
					</el-form-item>
					<el-form-item
						label="参赛人身份证号："
						:prop="`EmployeeInfos.${index}.CompeteIdNo`"
						:rules="[
							{
								required: false,
								message: '请输入参赛人员身份证号！',
								trigger: 'blur'
							},
							{
								pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X)$)/,
								message: '证件号码格式有误！',
								trigger: 'blur'
							}
						]"
					>
						<el-input v-model="item.CompeteIdNo" placeholder="请输入" />
					</el-form-item>
					<!-- <el-form-item v-if="item.isTeamShow" label="* 所属团队：">
						<el-select
							v-model="item.TeamId"
							:disabled="item.isChecked"
							@visible-change="handleVisibleChange(item.CompeteName, item.CompeteIdNo, index)"
							placeholder="请选择"
						>
							<el-option v-for="i in item.teamList" :label="i.teamName" :value="i.id" :key="i.id" :disabled="i.disabled" />
						</el-select>
						<el-checkbox
							style="margin-left: 20px"
							v-model="item.isChecked"
							@change="handleIsCheckedChange(index)"
							label="无团队"
						/>
					</el-form-item> -->
					<el-form-item
						label="参赛感应器："
						:prop="`EmployeeInfos.${index}.SensorNumber`"
						:rules="[
							{
								required: true,
								message: '请输入参赛的感应器！',
								trigger: 'blur'
							},
							{
								pattern: /^[0-9,]+$/,
								message: '感应号仅限输入数字和英文状态下的(,)',
								trigger: 'blur'
							}
						]"
					>
						<el-input v-model="item.SensorNumber" placeholder="请输入" />
					</el-form-item>
					<div v-if="!!applicationFrom.officialOrBusiness">
						<el-form-item label="船型：">
							<el-input v-model="item.shipType" placeholder="请输入" />
						</el-form-item>
						<el-form-item label="电机品牌/型号：">
							<el-input v-model="item.electricalType" placeholder="请输入" />
						</el-form-item>
						<el-form-item label="电调品牌/型号：">
							<el-input v-model="item.electricBrand" placeholder="请输入" />
						</el-form-item>
						<el-form-item label="电池品牌：">
							<el-input v-model="item.batteryType" placeholder="请输入" />
						</el-form-item>
						<el-form-item label="遥控品牌：">
							<el-input v-model="item.remoteControl" placeholder="请输入" />
						</el-form-item>
					</div>
					<div class="person_item_btn">
						<el-button
							v-if="index == applicationFrom.EmployeeInfos.length - 1"
							@click="NewPersonClick"
							size="small"
							type="primary"
							>新增</el-button
						>
						<el-button @click="DeletePersonClick(index)" size="small" type="danger">删除</el-button>
					</div>
				</div>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleCancelClick(ruleFormRef)">取消</el-button>
					<el-button type="primary" @click="handleSubmitClick(ruleFormRef)"> 提交 </el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 选择人员 -->
		<el-dialog v-model="menberMode" title="选择人员">
			<el-table ref="multipleTableRef" :data="notGroupedMember" style="width: 100%">
				<el-table-column property="isChecked" label="选择" align="center" width="100">
					<template #default="scope">
						<el-checkbox v-model="scope.row.isChecked" size="small" />
					</template>
				</el-table-column>
				<el-table-column
					:property="competitionProjectType == 2 ? 'competeName' : 'competeTeamName'"
					align="center"
					:label="competitionProjectType == 2 ? '姓名' : '队伍名称'"
				/>
				<el-table-column v-if="competitionProjectType == 2" property="sensorNumber" align="center" label="传感器" />
			</el-table>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="menberMode = false">取消</el-button>
					<el-button type="primary" @click="handleSelectCofirmClick"> 确认 </el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ElMessage, ElNotification, ElMessageBox, FormInstance, FormRules } from "element-plus";
import type { Action } from "element-plus";
import { CircleCloseFilled, CirclePlus } from "@element-plus/icons-vue";
import { useRoute } from "vue-router";
import { reactive, ref, h, watch, computed } from "vue";
// import employee from "@/api/modules/employee";
import api from "@/api/modules/competitionProject";
import groupingApi from "@/api/modules/competitionGroupingInfo";
import regApi from "@/api/modules/registarationinfo";
import { phoneFormat } from "@/utils/util";
import draggable from "vuedraggable";
import { GlobalStore } from "@/stores";
const { themeConfig } = GlobalStore();
const primary = computed(() => {
	return themeConfig.primary;
});
/* hooks */
const route = useRoute();
//定时器
let timer: any = null;
const drag = ref(false);
/**
 * ts type
 */
//成员列表type
interface Table {
	competeIdNo?: string;
	competeName: string;
	competeTeamName?: string;
	competeTel?: string;
	id: string;
	sensor: string;
	teamId?: string;
	teamName?: string;
	isChecked?: boolean;
	name?: string;
	nolocation?: number;
	children?: any;
	competeTeamInfos?: any;
	competeTeamId?: string;
}
//分组表单type
interface Grouping {
	total: number;
	min: number | null;
	max: number | null;
	groupingNumber: number | null;
	// perNum: number;
}
// 编辑队伍信息表格
const eiditTableData = ref();
// 编辑队伍信息双层下标
const eiditTableIndex = reactive({
	index: 0,
	i: 0
});
//随机分组表单Ref实例
const ruleFormRef = ref<FormInstance>();
//判断报名赛事项目类型（团队赛 or 个人赛）
const competitionProjectType = ref<number>(2);
//成员列表
const tableData = ref<Array<Table>>([]);
//存放参赛多余人员列表
const notGroupedMember = ref<Array<Table>>([]);
//添加报名表单数据
const applicationFrom = ref<Application.ApplicationOptions>({
	CompetitionId: route.query.competitionId as string, //赛事ID
	CompetitionProjectId: route.query.id as string, //比赛项目ID
	RegistrationSource: 3, //报名来源（1：小程序；2：H5；3：线下报名）
	RequestSource: 1,
	officialOrBusiness: parseInt(route.query.officialOrBusiness as string) as 0 | 1,
	EmployeeInfos: [
		{
			CompeteName: "", //参赛人姓名
			CompeteTel: "", //参赛人电话
			TeamId: "", //团队ID
			CompeteIdNo: "", //参赛人身份证号码
			SensorNumber: "", //感应器
			CompeteTeamName: "", //参赛队名
			openId: "",
			shipType: "",
			batteryType: "",
			remoteControl: "",
			electricalType: "",
			electricBrand: "",
			isChecked: false
		}
	]
});
//页面头部信息
const projectHeaderInfo = ref<any>({
	competitionName: route.query.competitionName,
	projectNmae: route.query.name
});
//添加报名模态框显示
const ApplicationModle = ref<boolean>(false);
//选择人员模态框显示
const menberMode = ref<boolean>(false);
// 团队赛编辑队伍信息弹出框
const eiditModel = ref<boolean>(false);
//添加报名表单无团队输入框禁用状态
// const isChecked = ref<boolean>(false);
//保存选择人员列表索引
const selectMemberIndex = ref<number>(0);
//保存如果有分组信息的场次id
const applicationEventsSsionId = ref<string>("");
// //获取项目参赛成员列表
const getData = async () => {
	let id = route.query.id;
	let { result } = await api.GetGroupListApi({ id });
	let { code, data } = result;
	if (code != 200) {
		prompt("提示", "该项目暂无参赛人员可分组！");
		return;
	}
	tableData.value = data.map((item: Table) => {
		item.isChecked = false;
		return item;
	});
	let res = await api.GetCompetitionPorjectDetailsByIdApi(id as string);
	if (res.result.code !== 200) {
		return;
	}
	competitionProjectType.value = parseInt(res.result.data.gameType);
	projectHeaderInfo.value.projectNmae = res.result.data.name;
	if (competitionProjectType.value == 1) {
		tableData.value = tableData.value.map(i => {
			i.children = i.competeTeamInfos;
			return i;
		});
	}
};
getData();
/**
 * 封装提示信息
 * @param title 标题
 * @param msg 提示信息
 * @param color 文字颜色
 */
const prompt = (title: string = "提示", msg: string, color: string = "teal") => {
	ElNotification({
		title: title,
		message: h("i", { style: `color: ${color}` }, msg)
	});
};
// const isHaveGroping = ref<boolean>(false);
//开始分组
const handleStartMatchClcik = async () => {
	let { result } = await groupingApi.JudgeGroupinfoByEventsIdApi(route.query.id as string);
	let { eventsSessionId, isHave } = result.data;
	if (isHave) {
		// isHaveGroping.value = true;
		ElMessageBox.alert("此场次已有分组，是否查看分组！", "提示", {
			confirmButtonText: "确认",
			callback: async (action: Action) => {
				if (action == "cancel") {
					ElMessage({
						type: "info",
						message: `取消`
					});
					return;
				}
				let res = await groupingApi.GetGroupInfoListByEventSessionIdApi(eventsSessionId as string);
				let { code, data } = res.result;
				let { groupCompetetionInfos, grouplists } = data;
				if (code !== 200) {
					ElMessage({
						type: "error",
						message: `系统错误！`
					});
					return;
				}
				let newArr: Array<any> = new Array(groupCompetetionInfos.length).fill([]);
				newArr = groupCompetetionInfos.map((item: any) => {
					return [
						...item.grouplists.map((val: any) => {
							let result: Table = {
								id: val.employeeId,
								competeName: val.employeeName,
								sensor: val.sensor || "",
								children:
									val.competeTeamInfos.map((i: any) => {
										i.competeName = i.employeeName;
										i.competeIdNo = i.employeeIdNo;
										i.sensor = i.sensor;
										return i;
									}) || [],
								competeTeamId: val.competeTeamId,
								competeTeamName: val.competeTeamName,
								isChecked: false
							};
							return result;
						})
					];
				});
				if (grouplists.length) {
					notGroupedMember.value = grouplists.map((val: any) => {
						let result: Table = {
							id: val.employeeId,
							competeName: val.employeeName,
							sensor: val.sensor || "",
							children:
								val.competeTeamInfos.map((i: any) => {
									i.competeName = i.employeeName;
									i.competeIdNo = i.employeeIdNo;
									i.sensor = i.sensor;
									return i;
								}) || [],
							competeTeamId: val.competeTeamId,
							competeTeamName: val.competeTeamName,
							isChecked: false
						};
						return result;
					});
				}
				applicationEventsSsionId.value = eventsSessionId;
				groupingModel.data = newArr as never;
				console.log(groupingModel.data);

				groupingModel.isShow = true;
			}
		});
		return;
	}
	dialogShow.value = true;
	// isHaveGroping.value = false;
};
//分组列表
const groupingModel = reactive({
	isShow: false, //控制模态框显示隐藏
	data: [] as Array<Array<Table>>
});
//随机分组信息模态框显示隐藏
const dialogShow = ref<boolean>(false);
//随机分组信息表单
watch(
	() => tableData.value,
	(val: Array<Table>) => {
		GroupingFrom.total = val.length;
	}
);
const GroupingFrom = reactive<Grouping>({
	total: (tableData.value.length as number) || 0,
	min: null,
	max: null,
	groupingNumber: null
	// perNum: 10,
});
//随机分组表单规则验证
const rules = reactive<FormRules>({
	min: [
		{
			type: "number",
			required: true,
			message: "最小人数不能为空！",
			trigger: "blur"
		}
	],
	max: [
		{
			type: "number",
			required: true,
			message: "最大人数不能为空",
			trigger: "blur"
		}
	],
	groupingNumber: [
		{
			type: "number",
			required: true,
			message: "分组数量不能为空",
			trigger: "blur"
		}
	]
});
/**
 * @param n 随机数最大长度
 */
const randomNum = (n: number) => {
	let arr = [];
	let temp;
	for (let i = 0; i < n; i++) {
		arr[i] = i;
	}
	for (let j = 0; j < n; j++) {
		let index = Math.floor(Math.random() * n);
		temp = arr[n - 1];
		arr[n - 1] = arr[index];
		arr[index] = temp;
		n--;
	}
	return arr;
};
/**
 * @param min 分组最小人数
 * @param max 分组最大人数
 * @param match 分组数
 * @param data 人员列表
 */
const matchGroup = (min: number, max: number, match: number, data: Array<any>) => {
	let newArr = new Array(match).fill([]); //分组后的数组
	let maxLenth = 0; //分组最大人数
	let total = data.length; //总人数
	for (let i = 0; i < match; i++) {
		let newData: Array<any> = [];
		data.forEach(item => {
			newData.push(item);
		});
		let num = Math.floor(Math.random() * (max - min + 1) + min);
		maxLenth += num;
		let matchIndex = randomNum(num);
		newArr[i] = new Array(num).fill([]);
		newArr[i] = newArr[i].map((item: any, idx: number) => {
			item = newData[matchIndex[idx]];
			data = data.filter((val: any) => {
				return val != item;
			});
			return item;
		});
	}
	if (maxLenth == total) {
		return newArr;
	}
	return [];
};
/**
 *  表单提交按钮
 * @param formEl 表单dom实例
 */
const handleConfrimClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	let valid = await formEl.validate();
	if (!valid) {
		ElMessage.error("请补充信息！");
		return false;
	}
	let { total, min, max, groupingNumber } = GroupingFrom;
	let number: boolean = parseFloat((total / (min as number)).toFixed(2)) < (groupingNumber as number);
	let num: boolean = parseFloat((total / (max as number)).toFixed(2)) > (groupingNumber as number);
	if (number) {
		prompt("", "请合理安排分组！");
		return false;
	}
	if (num) {
		prompt("", "请合理安排分组！");
		return false;
	}
	if ((min as number) > total) {
		prompt("", "请合理安排分组！");
		return false;
	}
	if ((max as number) > total) {
		prompt("", "请合理安排分组！");
		return false;
	}
	// handleRest();
	timer = setInterval(() => {
		let arr = matchGroup(min as number, max as number, groupingNumber as number, tableData.value);
		if (arr.length) {
			groupingModel.data = arr as never;
			clearInterval(timer);
		}
	});
	dialogShow.value = false;
	// isHaveGroping.value = false;
	groupingModel.isShow = true;
};
//关闭分组
const handleCancelGroupingClick = () => {
	tableData.value = tableData.value.map((val: Table) => {
		val.isChecked = false;
		return val;
	});
	GroupingFrom.groupingNumber = null;
	GroupingFrom.max = null;
	GroupingFrom.min = null;
	groupingModel.isShow = false;
	notGroupedMember.value = [];
};
//重新分组
const handleRest = () => {
	handleCancelGroupingClick();
	dialogShow.value = true;
};
//选择人员
const handleSelectMenberClick = (item: any, index: number) => {
	if (!notGroupedMember.value.length) {
		prompt("提示", `没有剩余的参赛${competitionProjectType.value == 1 ? "队伍" : "人员"}可选择`, "");
		return;
	}
	selectMemberIndex.value = index; //保存下标
	menberMode.value = true;
};
//选择人员确认按钮
const handleSelectCofirmClick = () => {
	// let { max } = GroupingFrom;
	let i = selectMemberIndex.value;
	let arr: Array<Table> = notGroupedMember.value.filter((val: Table) => {
		return val.isChecked;
	});
	// 限制人员添加不得超过规定最大人数
	// let len: number = groupingModel.data[i].length;
	// if (len + arr.length > (max as number)) {
	// 	prompt("提示", `分组成员不得超过${max}人`, "red");
	// 	return;
	// }
	notGroupedMember.value = notGroupedMember.value.filter((val: Table) => {
		return !val.isChecked;
	});
	groupingModel.data[i].push(
		...arr.map((res: Table) => {
			res.isChecked = false;
			return res;
		})
	);
	menberMode.value = false;
};
//添加分组
const handleAddGrouped = () => {
	if (!notGroupedMember.value.length) {
		prompt("提示", "没有剩余的参赛人员可分配", "");
		return;
	}
	let { min, max } = GroupingFrom;
	let index: number = Math.floor(Math.random() * ((max as number) - (min as number) + 1) + (min as number));
	groupingModel.data.push([]);
	notGroupedMember.value.forEach((item: Table, idx: number) => {
		if (idx > index) {
			return;
		}
		notGroupedMember.value = notGroupedMember.value.filter((val: Table) => {
			return val.id !== item.id;
		});
		groupingModel.data[groupingModel.data.length - 1].push(item);
	});
};
/**
 * 删除分组列表
 * @param item 列表信息
 * @param index 列表索引
 */
const handleDeleteGroupClick = (item: Array<Table>, index: number) => {
	if (groupingModel.data.length <= 1) {
		prompt("提示", "操作有误！", "red");
		return;
	}
	groupingModel.data.splice(index, 1);
	notGroupedMember.value.push(
		...item.map((val: Table) => {
			val.isChecked = false;
			return val;
		})
	);
};
/**
 * 删除成员列表
 * @param item 列表信息
 * @param index 列表索引
 */
const handleDeleteMemberClick = (item: Array<Table>, index: number) => {
	// let { min } = GroupingFrom;
	//判断是否选中成员
	let bool = item.some((val: Table) => {
		return val.isChecked;
	});
	if (!bool) {
		prompt("提示", "请选择后在操作！", "red");
		return;
	}
	let arr: Array<Table> = groupingModel.data[index].filter((val: Table) => {
		return !val.isChecked;
	});
	let deleteArr: Array<Table> = groupingModel.data[index].filter((val: Table) => {
		return val.isChecked;
	});
	groupingModel.data[index] = arr;
	notGroupedMember.value.push(
		...deleteArr.map((val: Table) => {
			val.isChecked = false;
			return val;
		})
	);
};
//分组随机赛道
const handleLotteryClick = (item: Array<Table>, index: number) => {
	let len = item.length;
	let arr = randomNum(len);
	let newArr: any = [];
	arr.forEach(idx => {
		newArr.push(item[idx]);
	});
	groupingModel.data[index] = newArr as never;
};
/**
 * 团队分组打开编辑队伍信息
 * @param id 团队id
 */
const handleEiditTeamInfoClick = (data: Table[], index: number, i: number) => {
	eiditModel.value = true;
	eiditTableData.value = data;
	eiditTableIndex.index = index;
	eiditTableIndex.i = i;
};
const handleEiditTableTeamClick = () => {
	groupingModel.data[eiditTableIndex.i][eiditTableIndex.index].children = eiditTableData.value;
	eiditModel.value = false;
};
//转换索引为字母分组
const letterNumber = (index: number) => {
	let idx: number = index;
	let str = [];
	for (let i = 0; i < 26; i++) {
		str.push(String.fromCharCode(i + 65));
	}
	return str[idx];
};
/**
 * 添加报名
 */
//打开添加报名模态框
const handleAddApplictionClick = () => {
	ApplicationModle.value = true;
};
//取消报名
const handleCancelClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	ApplicationModle.value = false;
	applicationFrom.value = {
		CompetitionId: route.query.competitionId as string, //赛事ID
		CompetitionProjectId: route.query.id as string, //比赛项目ID
		RegistrationSource: 3, //报名来源（1：小程序；2：H5；3：线下报名）
		RequestSource: 1,
		officialOrBusiness: parseInt(route.query.officialOrBusiness as string) as 0 | 1,
		EmployeeInfos: [
			{
				CompeteName: "", //参赛人姓名
				CompeteTel: "", //参赛人电话
				TeamId: "", //团队ID
				CompeteIdNo: "", //参赛人身份证号码
				SensorNumber: "", //感应器
				CompeteTeamName: "", //参赛队名
				teamList: [],
				openId: "",
				shipType: "",
				batteryType: "",
				remoteControl: "",
				electricalType: "",
				electricBrand: "",
				isChecked: false
			}
		]
	};
};
//检测用户输入完姓名和身份证
// const handleIsTeamShowBlur = (index: number) => {
// 	let reg =
// 		/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;
// 	let { CompeteIdNo, CompeteName } = applicationFrom.value.EmployeeInfos[index];
// 	if (!CompeteName || !reg.test(CompeteIdNo)) {
// 		applicationFrom.value.EmployeeInfos[index].isTeamShow = false;
// 		return;
// 	}
// 	applicationFrom.value.EmployeeInfos[index].isTeamShow = true;
// };
// //打开所属团队下拉框
// const handleVisibleChange = async (RealName: string, IDNumber: string, index: number) => {
// 	let res = await employee.GetEmployeeTeamListApi({
// 		RealName, //姓名
// 		IDNumber //身份证号
// 	});
// 	let { data } = res.result;
// 	if (!data) {
// 		applicationFrom.value.EmployeeInfos[index].teamList = [
// 			{
// 				teamName: "没有所属团队",
// 				id: "",
// 				disabled: true
// 			}
// 		];
// 		return;
// 	}
// 	applicationFrom.value.EmployeeInfos[index].teamList = data;
// };
//添加报名成员
const NewPersonClick = () => {
	let person_item: Application.Participants = {
		CompeteName: "", //参赛人姓名
		CompeteTel: "", //参赛人电话
		TeamId: "", //团队ID
		CompeteIdNo: "", //参赛人身份证号码
		SensorNumber: "", //感应器
		CompeteTeamName: "", //参赛队名
		openId: "",
		isChecked: false
	};
	applicationFrom.value.EmployeeInfos.push(person_item);
};
//删除报名成员
const DeletePersonClick = (index: number) => {
	if (applicationFrom.value.EmployeeInfos.length <= 1) {
		prompt("提示", "禁止操作！");
		return;
	}
	applicationFrom.value.EmployeeInfos.splice(index, 1);
};
//提交报名按钮
const handleSubmitClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (valid) {
			let data: Application.ApplicationOptions = JSON.parse(JSON.stringify(applicationFrom.value));
			data.EmployeeInfos = data.EmployeeInfos.map((item: Application.Participants): Application.Participants => {
				delete item.isChecked;
				delete item.isTeamShow;
				delete item.teamList;
				return item;
			});
			regApi.AddRegistrationInfoApi(data).then((res: any) => {
				let { code, message } = res.result;
				if (code != 200) {
					prompt("", message, "red");
					return;
				}
				prompt("", message, "green");
				ApplicationModle.value = false;
				getData();
			});
		} else {
			prompt("", "请补全信息");
		}
	});
};
// //报名表单无团队选择事件
// const handleIsCheckedChange = (index: number) => {
// 	let bool = isChecked.value;
// 	isChecked.value = bool;
// 	if (bool) {
// 		applicationFrom.value.EmployeeInfos[index].TeamId = "";
// 	}
// };
//保存分组
const handleCorifmClick = () => {
	if (notGroupedMember.value.length) {
		prompt("提示", "还有参赛队伍或人员未分组！", "red");
		return;
	}
	let newArr: Array<any> = [];
	newArr = groupingModel.data.map((arr: any, index: number) => {
		arr = {
			competitionProjectId: route.query.id,
			eventsSessionId: applicationEventsSsionId.value || "",
			name: letterNumber(index) + "组",
			grouplist:
				arr.map((val: any, idx: number) => {
					return (val = {
						employeeId: val.employeeId || val.id || "",
						noLocation: ++idx,
						sensor: val.sensor || "",
						competeTeamId: val.competeTeamId || "",
						competeTeamInfos: val?.children || []
					});
				}) || []
		};
		return arr;
	});
	groupingApi.AddCompetitionGroupingInfoApi(newArr).then((res: any) => {
		let { code, message } = res.result;
		prompt("提示", message, "");
		if (code !== 200) {
			return;
		}
		groupingModel.isShow = false;
	});
};

// 拖拽分组
const onStart = () => {
	drag.value = true;
};
const onEnd = () => {
	drag.value = false;
};
</script>

<style lang="scss" scoped>
::v-deep.el-overlay {
	.el-overlay-dialog {
		.el-dialog {
			.el-dialog__header {
				display: none !important;
			}
		}
	}
}
.tab_box {
	display: flex;
	align-items: center;
	justify-content: center;
}
.groupingModel-header {
	display: flex;
	justify-content: space-between;
	margin-bottom: 10px;
}
::v-deep.table_box_drag {
	display: flex;
	flex-wrap: wrap;
	align-items: flex-start;
	justify-content: space-between;
	width: 100%;
	height: auto;
	.table_main_drag {
		box-sizing: border-box !important;
		width: 45%;
		height: 100%;
		padding: 10px !important;
		margin-right: 15px;
		.card-header {
			display: flex;
			justify-content: space-between;
			margin-bottom: 10px;
		}
	}
}
.worning {
	display: flex;
	align-items: center;
	margin: 15px 0;
	i {
		margin-right: 15px;
		font-size: 40px;
	}
}
.groupingModel {
	display: flex;
	flex-direction: column;
	.transmitBtn {
		display: flex;
		flex-direction: column;
		div {
			margin-top: 15px;
		}
	}
	.groupingTop {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.groupingBottom {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.transmitLine {
		display: flex;
		justify-content: space-around;
	}
	.groupingItem {
		width: 45%;
	}
}
.person_item {
	padding: 15px;
	margin-bottom: 15px;
	background: #f0f0f0;
	.person_item_btn {
		display: flex;
		justify-content: flex-end;
		width: 150px;
	}
}
td,
th {
	text-align: center;
	border: 1px solid #9999996d;
}
.dragClass {
	background-color: #dddddd;
}
.ghostClass {
	border: 1px solid #6aa3ff !important;
}
.chosenClass {
	color: #6aa3ff;
}
table {
	width: 100%;
	border-collapse: collapse;
}
table caption {
	margin: 1em 0;
	font-size: 2em;
	font-weight: bold;
}
table thead tr {
	color: #ffffff;
	background-color: v-bind(primary);
}
table tbody tr:nth-child(odd) {
	background-color: #eeeeee;
}
th {
	padding: 10px 0;
}
.notGrouped {
	margin-top: 40px;
	table {
		position: relative;
		display: block;
		width: 100%;
	}
	thead {
		float: left;
	}
	tbody tr {
		display: inline-block;
		td {
			display: -webkit-box;
			overflow: hidden;
			text-overflow: ellipsis;
			-webkit-line-clamp: 1;
			-webkit-box-orient: vertical;
		}
	}
	th,
	td {
		display: block;
		width: 60px;
		height: 45px;
		padding: 0 10px !important;
		line-height: 45px;
		text-align: center;
	}
}
</style>
<style lang="scss">
.el-dialog.is-fullscreen.garoup-dialog {
	position: relative;
	min-height: 100vh;
	.el-dialog__header {
		display: none !important;
	}
	.close-btn {
		position: absolute;
		top: 10px;
		right: 10px;
	}
	.dialog-footer {
		position: fixed;
		right: 20px;
		bottom: 20px;
	}
}
</style>
